package com.zlsy.secondtime.threadcoreknowledge.volatiledemo;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zhouliang
 * @date 2020/5/15 20:08
 */
public class NonInterruptibleBlocking implements Runnable {

    private CountDownLatch latch;
    private int i;

    private NonInterruptibleBlocking(CountDownLatch latch, int i) {
        this.latch = latch;
        this.i = i;
    }

    public static void main(String[] args) {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                4,
                8,
                0L,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(1024),
                new BasicThreadFactory.Builder().namingPattern("NonInterruptibleBlocking-%s").build(),
                new ThreadPoolExecutor.AbortPolicy()
        );

        CountDownLatch latch = new CountDownLatch(10);

        for (int i = 0; i < 10; i++) {
            NonInterruptibleBlocking r = new NonInterruptibleBlocking(latch, i);
            poolExecutor.execute(r);
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        poolExecutor.shutdown();
    }

    @Override
    public void run() {
        try {
            System.out.println("当前线程:" + Thread.currentThread().getName() + "输出:" + i);
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            latch.countDown();
        }

    }
}
